package com.xiaoshuidi.cloud.module.iot.controller.admin.doorlock;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.xiaoshuidi.cloud.module.iot.annotation.OperationDataAccessAnnotation;
import com.xiaoshuidi.cloud.module.iot.api.device.vo.AddPasswordModelVo;
import com.xiaoshuidi.cloud.module.iot.common.ResultModel;
import com.xiaoshuidi.cloud.module.iot.dal.model.doorLock.*;
import com.xiaoshuidi.cloud.module.iot.enums.ApiConstants;
import com.xiaoshuidi.cloud.module.iot.enums.RedisTypeEnum;
import com.xiaoshuidi.cloud.module.iot.service.CacheService;
import com.xiaoshuidi.cloud.module.iot.service.DoorLockService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 门锁操作
 *
 * @author arvin
 * @date 2019-04-10 09:01
 * @description
 */
@RestController
@Tag(name = "智能设备 - 智能门锁")
@RequestMapping(ApiConstants.NAME + "/doorlock")
public class DoorLockController {
    private static final Logger LOGGER = LoggerFactory.getLogger(DoorLockController.class);

    @Autowired
    private DoorLockService doorLockService;

    @Autowired
    private CacheService cacheService;

    /**
     * 开门记录
     *
     * @param doorLockReportReqVO
     * @return
     */
    @Operation(summary = "开门记录")
    @Parameter(name = "doorLockReportReqVO", description = "开门记录实体类")
    @PostMapping("/manage/getOpenDoorRecord")
    public ResultModel<PageInfo<DoorLockReportRespVO>> getOpenDoorRecord(@RequestBody DoorLockReportReqVO doorLockReportReqVO) {
        ResultModel<PageInfo<DoorLockReportRespVO>> resultModel = null;
        resultModel = doorLockService.getOpenDoorRecord(doorLockReportReqVO);
        return resultModel;
    }

    /**
     * 门锁操作记录仪
     *
     * @param doorLockReportReqVO
     * @return
     */
    @Operation(summary = "门锁操作记录仪")
    @Parameter(name = "doorLockReportReqVO", description = "开门记录实体类")
    @PostMapping("/manage/getOperationRecord")
    public ResultModel<PageInfo<DoorLockOperationRecord>> getOperationRecord(@RequestBody DoorLockReportReqVO doorLockReportReqVO) {
        ResultModel<PageInfo<DoorLockOperationRecord>> resultModel = null;
        resultModel = doorLockService.getOperationRecord(doorLockReportReqVO);
        return resultModel;
    }

    /**
     * 门锁详情
     *
     * @param deviceNo
     * @return
     */
    @Operation(summary = "门锁详情")
    @Parameter(name = "deviceNo", description = "设备编号")
    @GetMapping("manage/getDoorlockInfo")
    public ResultModel<DoorLockInfo> getDoorlockInfo(@RequestParam("deviceNo") String deviceNo) {
        ResultModel<DoorLockInfo> resultModel = null;
        resultModel = doorLockService.getDoorlockInfo(deviceNo);
        return resultModel;
    }


    /**
     * 门锁刷新
     *
     * @param deviceNo
     * @return
     */
    @Operation(summary = "门锁刷新")
    @Parameter(name = "deviceNo", description = "设备编号")
    @GetMapping("/manage/refreshDoorLoclInfo")
    public ResultModel<DoorLockInfo> refreshDoorLoclInfo(@RequestParam("deviceNo") String deviceNo) {
        ResultModel<DoorLockInfo> resultModel = null;
        try {
            resultModel = doorLockService.refreshDoorLoclInfo(deviceNo);
        } catch (Exception e) {
            resultModel = ResultModel.createNativeFail("刷新失败");
        }
        return resultModel;
    }

    /**
     * 冻结密码
     *
     * @param addPasswordModel
     * @return
     */
    @Operation(summary = "冻结密码")
    @Parameter(name = "addPasswordModel", description = "密码实体类")
    @OperationDataAccessAnnotation
    @PostMapping("password/frozenPassword")
    public ResultModel<AddPasswordModel> frozenPassword(@RequestBody AddPasswordModel addPasswordModel) {
        LOGGER.info("gataway->doorlock,冻结密码请求参数userId:{},AddPasswordModel:{}", JSONObject.toJSONString(addPasswordModel));
        ResultModel<AddPasswordModel> resultModel = null;
        try {
            resultModel = doorLockService.frozenPassword(addPasswordModel);
        } catch (Exception e) {
            resultModel = ResultModel.createNativeFail("冻结密码失败");
        }
        return resultModel;
    }

    /**
     * 解冻密码
     *
     * @param addPasswordModel
     * @return
     */
    @Operation(summary = "解冻密码")
    @Parameter(name = "addPasswordModel", description = "密码实体类")
    @OperationDataAccessAnnotation
    @PostMapping("password/unfrozenPassword")
    public ResultModel<AddPasswordModel> unfrozenPassword(@RequestBody AddPasswordModel addPasswordModel) {
        LOGGER.info("gataway->doorlock,解冻密码请求参数,AddPasswordModel:{}", JSONObject.toJSONString(addPasswordModel));
        ResultModel<AddPasswordModel> resultModel = null;
        try {
            resultModel = doorLockService.unfrozenPassword(addPasswordModel);
        } catch (Exception e) {
            resultModel = ResultModel.createNativeFail("解冻密码失败");
        }
        return resultModel;
    }


    /**
     * 删除密码
     *
     * @param addPasswordModel
     * @return
     */
    @Operation(summary = "删除密码")
    @Parameter(name = "addPasswordModel", description = "密码实体类")
    @OperationDataAccessAnnotation
    @PostMapping("password/deletePassword")
    public ResultModel<AddPasswordModelVo> deletePassword(@RequestBody AddPasswordModelVo addPasswordModel) {
        LOGGER.info("gataway->doorlock,删除密码请求参数,AddPasswordModel:{}", JSONObject.toJSONString(addPasswordModel));
        ResultModel<AddPasswordModelVo> resultModel = null;
        try {
            resultModel = doorLockService.deletePassword(addPasswordModel);
        } catch (Exception e) {
            LOGGER.error("删除密码失败: ", e);
            resultModel = ResultModel.createNativeFail("删除密码失败");
        }
        return resultModel;
    }


    /**
     * 密码修改（在线）
     *
     * @param addPasswordModel
     * @return
     */
    @Operation(summary = "密码修改（在线）")
    @Parameter(name = "addPasswordModel", description = "密码实体类")
    @OperationDataAccessAnnotation
    @PostMapping("password/updatePassword")
    public ResultModel<AddPasswordModel> updatePassword(@RequestBody AddPasswordModel addPasswordModel) {
        LOGGER.info("gataway->doorlock,修改密码请求参数,AddPasswordModel:{}", JSONObject.toJSONString(addPasswordModel));
        ResultModel<AddPasswordModel> resultModel = null;
        try {
            resultModel = doorLockService.updatePassword(addPasswordModel);
        } catch (Exception e) {
            resultModel = ResultModel.createNativeFail("修改密码失败");
        }
        return resultModel;
    }


    /**
     * 下发密码
     *
     * @param addPasswordModel
     * @return
     */
    @Operation(summary = "下发密码")
    @OperationDataAccessAnnotation
    @Parameter(name = "addPasswordModel", description = "密码实体类")
    @PostMapping("/password/addPassword")
    public ResultModel<AddPasswordModel> addPassword(@RequestBody AddPasswordModel addPasswordModel) {
        LOGGER.info("gataway->doorlock,下发密码请求参数,AddPasswordModel:{}", JSONObject.toJSONString(addPasswordModel));
        ResultModel<AddPasswordModel> resultModel = null;
        try {
            //下发门锁密码防重
            String key = new StringBuilder().append(RedisTypeEnum.SDIOT_REFRESHDOORLOCK.getCode()).append(addPasswordModel.getDeviceNo()).toString();
            if (cacheService.setIfAbsent(key, addPasswordModel.getDeviceNo())) {
                cacheService.expire(key, 60);
                addPasswordModel.setMobile(addPasswordModel.getMobile().replaceAll(" ", ""));
                resultModel = doorLockService.addPassword(addPasswordModel);
                cacheService.deleteObjectByKey(key);
            } else {
                resultModel = ResultModel.createNativeFail("请勿重复下发密码");
            }

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("doorlock->下发密码请求,请求参数：{}，异常原因：{}", JSONObject.toJSONString(addPasswordModel), e);
            resultModel = ResultModel.createNativeFail(e.getMessage());
        }
        return resultModel;
    }

    /**
     * 门锁密码列表
     *
     * @param deviceNo
     * @return
     */
    @Operation(summary = "门锁密码列表")
    @Parameter(name = "deviceNo", description = "设备编号")
    @GetMapping("password/getPasswordList")
    public ResultModel<List<AddPasswordModel>> getPasswordList(@RequestParam("deviceNo") String deviceNo) {
        LOGGER.info("获取门锁密码列表请求参数：deviceNo:{}", deviceNo);
        ResultModel<List<AddPasswordModel>> resultModel = null;
        resultModel = doorLockService.getPasswordList(deviceNo, null);
        return resultModel;
    }
}
